<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { TClass } from '@/Types/education'
import { useUserStore } from '@/stores'
import { getClassListByUserIdService } from '@/api/user_classname'
import { getUserListByClassIdListService } from '@/api/user_classname'
import { getScoreListBySpecificService } from '@/api/education/score'
import { exportScoreToExcel } from '@/components/Class/exportScore'
import router from '@/router'

/**
 * 模块名: 成绩管理
 * 代码描述:
 * 作者:mck
 * 创建时间:2025/02/14 20:25:20
 */

/**
 * 初始化
 */
const userStore = useUserStore()
const classList = ref<TClass[]>([])
const loading = ref(false)
const currentClass = ref() // 当前班级

// 班级按年级分组
const classListByGrade = computed(() => {
	const groupedClasses: { [key: string]: TClass[] } = {}

	classList.value.forEach((cls) => {
		const grade = cls.grade || '未知年级'
		if (!groupedClasses[grade]) {
			groupedClasses[grade] = []
		}
		groupedClasses[grade].push(cls)
	})

	// 将结果转换为排序后的数组格式，方便在模板中使用
	return Object.entries(groupedClasses)
		.sort(([gradeA], [gradeB]) => gradeB.localeCompare(gradeA)) // 按年级降序排列
		.map(([grade, classes]) => ({
			grade,
			classes: classes.sort((a, b) =>
				(a.classname || '').toString().localeCompare((b.classname || '').toString())
			)
		}))
})

/**
 * 模块名: 数据获取
 */
// 获取班级数据
const getClassInfo = async () => {
	try {
		loading.value = true
		const res = await getClassListByUserIdService(userStore.userInfo.userInfo.userId)
		if (res.data.code === 1) {
			classList.value = res.data.data.map((item: TClass) => ({
				...item
			}))
		}
	} catch (error) {
		ElMessage.error('获取班级数据失败')
	} finally {
		loading.value = false
	}
}

/**
 * 数据格式化
 */
// 格式化学历名称
const formatLevelName = (level: string | undefined) => {
	if (level === undefined) return ''
	return level === 'undergrad' ? '本科' : '专科'
}
// 格式化班级名称
const formatClassName = (className: string | number | undefined) => {
	if (className === undefined) return ''
	return String(className).includes('班') ? className : className + '班'
}

/**
 * 生命周期
 */
onMounted(async () => {
	await getClassInfo()
})

/**
 * 页面操作
 */
// 选择班级
const handleSelectClass = (classId: number | undefined) => {
	if (classId !== undefined) {
		currentClass.value = classId
		// 可以在此处添加选择班级后的操作
	}
}

// 点击查询
const handleQuery = async (classId: number | undefined) => {
	if (classId === undefined) return

	router.push({
		path: `/classScoreInfo/${classId}`
	})
}

// 导出成绩
const handleExport = async (
	classId: number | undefined,
	className: string | number | undefined
) => {
	if (classId === undefined) return

	try {
		// 显示加载状态
		loading.value = true

		// 获取班级学生信息
		const studentsRes = await getUserListByClassIdListService(1, [classId])
		if (studentsRes.data.code !== 1) {
			ElMessage.error('获取学生信息失败')
			return
		}

		// 获取成绩数据
		const scoreRes = await getScoreListBySpecificService({
			classId: classId,
			academicYear: '2023-2024' // 默认使用当前学年
		})

		if (scoreRes.data.code !== 1) {
			ElMessage.error('获取成绩数据失败')
			return
		}

		// 构建学生成绩数据结构
		const studentData = studentsRes.data.data.map((student: any) => {
			// 初始化学生数据结构
			const studentScoreData = {
				studentId: student.typeNumber,
				name: student.uname,
				scores: {
					theory: {},
					practice: {}
				}
			}

			// 查找该学生的所有成绩记录
			const scores = scoreRes.data.data.filter((score: any) => score.studentId === student.userId)

			// 如果有成绩记录，整合该学生的理论和实践成绩
			if (scores.length > 0) {
				scores.forEach((score: any) => {
					studentScoreData.scores.theory = {
						status: score.aboutTheory || 'normal',
						midTerm: score.midTermTheory,
						final: score.finalTheory,
						usual: score.usualTheory,
						total: score.theoryTotal
					}

					studentScoreData.scores.practice = {
						status: score.aboutPractice || 'normal',
						midTerm: score.midTermPractice,
						final: score.finalPractice,
						usual: score.usualPractice,
						total: score.practiceTotal
					}
				})
			}

			return studentScoreData
		})

		// 确认导出
		ElMessageBox.confirm(`确认导出 ${formatClassName(className)} 成绩数据?`, '导出确认', {
			confirmButtonText: '确认导出',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				// 执行导出
				try {
					exportScoreToExcel(studentData, `${formatClassName(className)}班成绩单`)
					ElMessage.success(`导出 ${formatClassName(className)} 成绩成功`)
				} catch (error) {
					console.error('导出失败:', error)
					ElMessage.error('导出失败，请稍后重试')
				}
			})
			.catch(() => {
				ElMessage.info('已取消导出')
			})
	} catch (error) {
		console.error('导出过程出错:', error)
		ElMessage.error('导出过程出错，请稍后重试')
	} finally {
		loading.value = false
	}
}
</script>

<template>
	<div class="score-manage">
		<el-card shadow="hover" v-loading="loading">
			<!-- 顶部操作区 -->
			<template #header>
				<div class="card-header">
					<div class="left-section">
						<span>成绩管理</span>
					</div>
				</div>
			</template>

			<!-- 按年级分组的班级列表 -->
			<div class="grade-sections">
				<el-empty v-if="classListByGrade.length === 0" description="暂无班级数据" />

				<div v-for="gradeGroup in classListByGrade" :key="gradeGroup.grade" class="grade-section">
					<div class="grade-header">
						<h3>{{ gradeGroup.grade }}级</h3>
					</div>

					<div class="class-cards">
						<div
							v-for="cls in gradeGroup.classes"
							:key="cls.classId"
							class="class-card"
							:class="{ active: currentClass === cls.classId }"
							@click="handleSelectClass(cls.classId)"
						>
							<div class="class-info">
								<div class="class-name">
									{{ formatClassName(cls.classname) }}
								</div>
								<div class="class-detail">
									<span class="level">{{ formatLevelName(cls.level) }}</span>
									<span class="major">{{ cls.major }}</span>
								</div>
							</div>
							<div class="card-actions">
								<el-button type="primary" size="small" @click.stop="handleQuery(cls.classId)"
									>查询</el-button
								>
								<el-button
									type="success"
									size="small"
									@click.stop="handleExport(cls.classId, cls.classname)"
									>导出</el-button
								>
							</div>
						</div>
					</div>
				</div>
			</div>
		</el-card>
	</div>
</template>

<style scoped lang="scss">
.score-manage {
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.left-section {
			font-size: 16px;
			font-weight: bold;
		}
	}

	.grade-sections {
		display: flex;
		flex-direction: column;
		gap: 20px;

		.grade-section {
			.grade-header {
				margin-bottom: 10px;
				padding-bottom: 5px;
				border-bottom: 1px solid var(--el-border-color-light);

				h3 {
					font-size: 16px;
					margin: 0;
					color: var(--el-text-color-primary);
				}
			}

			.class-cards {
				display: flex;
				flex-wrap: wrap;
				gap: 15px;

				.class-card {
					width: 180px;
					height: 150px; /* 增加高度容纳按钮 */
					padding: 15px;
					border-radius: 6px;
					border: 1px solid var(--el-border-color);
					display: flex;
					flex-direction: column;
					justify-content: space-between; /* 改为空间分布 */
					cursor: pointer;
					transition: all 0.3s;
					background-color: var(--el-fill-color-lighter);

					&:hover {
						box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
						transform: translateY(-3px);
					}

					&.active {
						background-color: var(--el-color-primary-light-9);
						border-color: var(--el-color-primary);
					}

					.class-info {
						text-align: center;

						.class-name {
							font-size: 18px;
							font-weight: bold;
							margin-bottom: 10px;
							color: var(--el-text-color-primary);
						}

						.class-detail {
							font-size: 14px;
							color: var(--el-text-color-secondary);
							display: flex;
							justify-content: center;
							gap: 10px;

							.level,
							.major {
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							}
						}
					}

					.card-actions {
						display: flex;
						justify-content: space-between;
						gap: 8px;
						margin-top: 15px;

						.el-button {
							flex: 1;
							padding: 5px;
						}
					}
				}
			}
		}
	}
}

:deep(.el-card__header) {
	padding: 15px;
}
</style>
